package com.wx.house.common.base;

import com.wx.house.common.exception.BusinessException;
import com.wx.house.common.exception.UserException;
import com.wx.house.common.util.JwtUtils;
import com.wx.house.core.pojo.base.UserInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @Author ：罗棋
 * @Email ：58428467@qq.com
 * @date ：Created in 2019/11/01 上午 11:29
 * @description：
 * @version: ：V
 */
public class UserInfoUtil {

public static UserInfo userInfo() {
	HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
	//String token = "eyJhbGciOiJIUzUxMiJ9.eyJpc3MiOiLnqLPkv6Hnp5HmioAiLCJpYXQiOjE1NzI1Nzk0MjksImV4cCI6MjU3MjU3OTQyOCwicmVhbE5hbWUiOiJsdW9xaSIsImxldmVsIjoiMC4xNTcyMzM2NTk5MjI1OTc5LjE1NzIzMzcyMDU3MjIyOTUiLCJhY2NvdW50VHlwZSI6IjIiLCJpZCI6IjE1NzIzMzcyMDU3MjIyOTUiLCJtQWNjSWQiOiIxNTcyMzM2NTk5MjI1OTc5In0.TLzxcLZJKe0TAzBDN1v5zosEZhhs0geDhX6FcN5c2c4f8AZONME0OLTxPXLiXvxlUYp02eGcSV6xFx9gk_-95A";
	String token = request.getHeader("authorization");
	Claims claims;
	try {
		claims = JwtUtils.builder().token(token).build().claims();
	} catch (Exception e) {
		e.printStackTrace();
		throw new UserException("您的登录已过期",601);
	}
//	catch (ExpiredJwtException ej) {
//		ej.printStackTrace();
//		throw new BusinessException("用户登陆信息过期");
//	} catch (IllegalArgumentException ia) {
//		ia.printStackTrace();
//		throw new BusinessException("用户token不能为空");
//	} catch (Exception e) {
//		e.printStackTrace();
//		throw new BusinessException("用户token格式不正确");
//	}
	UserInfo userInfo = new UserInfo();
	try {
		userInfo.setId(claims.get("id").toString());
		userInfo.setAccountType(claims.get("accountType").toString());
		userInfo.setLevel(claims.get("level").toString());
		userInfo.setMAccId(claims.get("mAccId").toString());
		userInfo.setRealName(claims.get("realName").toString());
		userInfo.setIss(claims.get("iss").toString());
		userInfo.setIat(claims.get("iat").toString());
		userInfo.setExp(claims.get("exp").toString());
		
		if (claims.get("accountType").toString().equals("0")) {
			userInfo.setMAccId(null);
		}
		if(claims.get("accountType").toString().equals("1")) {
			userInfo.setMAccId(userInfo.getId());
		}
	} catch (Exception ignored) {
	
	}
	return userInfo;
}
//	public static void main(String[] args) {
//		String token = "eyJhbGciOiJIUzUxMiJ9.eyJpc3MiOiLnqLPkv6Hnp5HmioAiLCJpYXQiOjE1NzcwNzA3MDEsImV4cCI6MTU3NzEyNDcwMSwicmVhbE5hbWUiOiLmlrDnlKjmiLciLCJsZXZlbCI6IjAuMTU3NjgyMjM3MTM1Njc4NCIsImFjY291bnRUeXBlIjoiMSIsImlkIjoiMTU3NjgyMjM3MTM1Njc4NCIsIm1BY2NJZCI6IjAifQ.hVw4In-egnRemHllADg-_8NBpbG9jWdFBPvJbftLNzJLLfthATO-ECae2Tq8jynKrKDKdLs1ra13p_MJ5ugLeA";
//		userInfo(token);
//	}
}
